package com.qf.watcher;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

public class ZookeeperWatcher {
    //    连接地址
    private static final String ZKADDR = "10.9.12.200:8601,10.9.12.200:8602,10.9.12.200:8603";
    //    用作阻塞的 1 的意思是只需要有1个地方 执行了放行   就放行所有阻塞的地方
    private static CountDownLatch countDownLatch=new CountDownLatch(1);
    private  static ZooKeeper zooKeeper;
    public static void main(String[] args) throws Exception {
            System.out.println("11111");

        zooKeeper=new ZooKeeper(ZKADDR, 5000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                Event.KeeperState state = watchedEvent.getState();
                String path = watchedEvent.getPath();
                Event.EventType type = watchedEvent.getType();
                System.out.println("666666666");
                System.out.println("state-->"+state);
                System.out.println("path-->"+path);
                System.out.println("type-->"+type);

                switch (state){
                    case SyncConnected:
                        if(type== Event.EventType.NodeCreated){
                            byte[] data = new byte[0];
                            try {
                                data = zooKeeper.getData(path, false, null);
                                System.out.println("77777777");
                                System.out.println(path+"创建了 传递的内容是"+new String(data));
                            } catch (KeeperException e) {
                                e.printStackTrace();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                }

                countDownLatch.countDown();
            }
        });
        System.out.println("22222");
        countDownLatch.await();
        System.out.println("33333");

//        判断某个节点是否存在  因为有watcher 所有 是true
//        监听要 先监听后操作才可以
        Stat stat = zooKeeper.exists("/dsdssssss12345", true);
        System.out.println(stat);

        String s = zooKeeper.create("/dsdssssss12345", "dsds".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("节点名字"+s);
        countDownLatch.await();
        System.out.println("44444");

        System.in.read();
        System.out.println("55555");



    }
}
